<template>
  <div class="profile-container">
    <el-header class="profile-header">
      <div class="header-content">
        <div class="header-left">
          <img src="@/assets/logo.svg" alt="Logo" class="logo">
          <h1 class="title">个人信息</h1>
        </div>
        <div class="header-right">
          <div class="user-info">
            <el-icon class="user-icon"><User /></el-icon>
            <span class="nickname">{{ userInfo.nickname || userInfo.username }}</span>
          </div>
          <el-button type="danger" @click="logout" size="large">退出登录</el-button>
        </div>
      </div>
    </el-header>

    <el-main class="profile-main">
      <el-card class="profile-card">
        <template #header>
          <div class="card-header-content">
            <span class="card-title">个人信息</span>
            <el-button type="primary" @click="showPasswordDialog = true">修改密码</el-button>
          </div>
        </template>

        <el-form ref="profileForm" :model="userInfo" label-width="100px">
          <el-form-item label="用户名">
            <el-input v-model="userInfo.username" readonly />
          </el-form-item>

          <el-form-item label="昵称">
            <el-input v-model="userInfo.nickname" readonly />
          </el-form-item>

          <el-form-item label="邮箱">
            <el-input v-model="userInfo.email" type="email" readonly />
          </el-form-item>

          <el-form-item label="电话">
            <el-input v-model="userInfo.phone" readonly />
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 修改密码对话框 -->
      <el-dialog
        v-model="showPasswordDialog"
        title="修改密码"
        width="500px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordFormRules"
          label-width="120px"
        >
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              placeholder="请输入旧密码"
              show-password
            />
          </el-form-item>

          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              show-password
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="showPasswordDialog = false">取消</el-button>
            <el-button type="primary" @click="handleUpdatePassword">确认修改</el-button>
          </div>
        </template>
      </el-dialog>
    </el-main>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { User, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

const userInfo = reactive({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  gender: 'male',
  birthday: null,
  avatar: '',
  introduction: ''
})

const profileForm = ref(null)

// 修改密码相关
const showPasswordDialog = ref(false)
const passwordFormRef = ref(null)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码表单验证规则
const passwordFormRules = reactive({
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' },
    { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, message: '密码必须包含大小写字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ]
})

// 修改密码
const handleUpdatePassword = async () => {
  try {
    if (!passwordFormRef.value) return
    await passwordFormRef.value.validate()
    
    // 获取当前登录用户信息
    const storedUser = localStorage.getItem('user')
    if (!storedUser) {
      ElMessage.error('未找到用户信息，请重新登录')
      router.push('/login')
      return
    }
    
    const currentUser = JSON.parse(storedUser)
    const userId = currentUser.userId || currentUser.user_id || currentUser.id
    
    if (!userId) {
      ElMessage.error('无法获取用户ID')
      return
    }
    
    // 调用后端修改密码接口
    const res = await axios.put(`/users/${userId}/password`, {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    
    if (res.data.code === 200) {
      ElMessage.success('密码修改成功')
      showPasswordDialog.value = false
      // 重置表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    } else {
      ElMessage.error(res.data.msg || '密码修改失败')
    }
  } catch (err) {
    console.error('修改密码错误:', err)
    if (err.response && err.response.data) {
      ElMessage.error(err.response.data.msg || '密码修改失败')
    } else {
      ElMessage.error('密码修改失败，请检查网络连接')
    }
  }
}

// 加载用户信息
const loadUserInfo = () => {
  try {
    // 从localStorage获取当前登录用户信息
    const storedUser = localStorage.getItem('user')
    if (!storedUser) {
      ElMessage.error('未找到用户信息，请重新登录')
      router.push('/login')
      return
    }
    
    const currentUser = JSON.parse(storedUser)
    const userData = Array.isArray(currentUser) ? currentUser[0] : currentUser
    
    if (!userData) {
      ElMessage.error('无法解析用户信息，请重新登录')
      router.push('/login')
      return
    }
    
    // 直接使用localStorage中的用户信息（兼容不同字段名）
    userInfo.username = userData.username || userData.user_name || ''
    userInfo.nickname = userData.nickname || userData.user_nickname || ''
    userInfo.email = userData.email || userData.user_email || ''
    userInfo.phone = userData.phone || userData.user_phone || ''
  } catch (err) {
    console.error('加载用户信息错误:', err)
    ElMessage.error('加载用户信息失败，请重新登录')
    router.push('/login')
  }
}

// 退出登录
const logout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('user')
  router.push('/')
}

// 页面加载完成后获取用户信息
onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.profile-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.profile-header {
  background-color: #ffffff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 40px;
  height: 80px;
  box-sizing: border-box;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.logo {
  width: 50px;
  height: 50px;
  object-fit: contain;
}

.card-header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  color: #303133;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 16px;
}

.user-icon {
  font-size: 24px;
}

.nickname {
  font-weight: 500;
}

.profile-main {
  padding: 20px 40px;
  flex: 1;
  overflow: auto;
}

.profile-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}
</style>